package com.zyasdk.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.TimeZone;

import org.json.JSONException;

import android.content.Context;

import com.zyasdk.model.NewsPortal;
import com.zyasdk.util.SimpleHttp.ResultCallBack;

public class NewsUtil {
	public interface NewsResultCallBackListener {
		public void callback(List<NewsPortal> newsList);
	}

	/**
	 * 请求数据
	 */
	public static void getData(final Context context,
			final NewsResultCallBackListener cblistener) {
		HashMap<String, String> hm = new LinkedHashMap<String, String>();
		hm.put("channel", "265ee3e8-b2b6-11e5-a237-00163e003029");
		hm.put("country", LanguageUtil.getCountry(context));
		hm.put("language", LanguageUtil.getLanguage(context));
		hm.put("limit", "30");
		hm.put("resolution", ScreenUtils.getScreenWidth(context) + "*"
				+ ScreenUtils.getScreenHeight(context));
		hm.put("dip", "2.0");
		hm.put("osv", "4.2");
		hm.put("nt", "wifi");
		hm.put("tzone", getTimeZone());
		StringBuilder builder = new StringBuilder(
				"http://api.newsportal.hk/v1/articles?");
		for (Entry<String, String> e : hm.entrySet()) {
			builder.append(e.getKey());
			builder.append("=");
			builder.append(e.getValue());
			builder.append("&");
		}
		builder.deleteCharAt(builder.length() - 1);
		SimpleHttp.request(builder.toString(), new ResultCallBack() {

			@Override
			public void result(String result) {
				try {
					if (result != null) {
						ArrayList<NewsPortal> ll = (ArrayList<NewsPortal>) new ParserUtil()
								.parserNewsPortal(result);
						//如果当前语言环境是英文则将不是中文的数据排除掉
						if (LanguageUtil.getDefaultLanguage(context).equals(
								"cn")) {
							for (int i = 0; i < ll.size(); i++) {
								NewsPortal np = ll.get(i);
								if (!LanguageUtil.isChinese(np.getHeader())) {
									ll.remove(np);
								}
							}
						}
						if (cblistener != null)
							cblistener.callback(ll);
					} else {
						if (cblistener != null)
							cblistener.callback(null);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					if (cblistener != null)
						cblistener.callback(null);
				}
			}
		});
	}

	/**
	 * 获取时区
	 * 
	 * @return
	 */
	private static String getTimeZone() {
		TimeZone tz = TimeZone.getDefault();
		String s = tz.getDisplayName(false, TimeZone.SHORT);
		if (s.startsWith("GMT")) {
			s = s.replace("GMT", "");
		} else if (s.startsWith("UTC")) {
			s = s.replace("UTC", "");
		}
		try {
			s = URLEncoder.encode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}
}
